import React, { useState, useMemo, useEffect } from 'react'
import { LeftOutlined, HomeFilled, PlayCircleTwoTone, PauseCircleTwoTone } from '@ant-design/icons'
// import {message} from 'antd'
import './musicdetail.scss'
import axios from 'axios'
import { useRef } from 'react'
export default function Musicdetail(props) {
    useEffect(() =>{
        getmusicdetail()
        // eslint-disable-next-line
    },[])
    // 监听中间圆盘转动以及开始/停止播放
    let [play, setplay] = useState(true)
    // 播放地址
    let [musicurl, setmusicurl] = useState({})
    // 歌词
    let [word, setword] = useState([])
    // 当前播放歌词行id
    let [currentlyc, setcurrentlyc] = useState(0)
    // 监听歌词两种样式
    let [getword, setgetword] = useState(false)
    // audio元素的ref
    const audioRef = useRef(null)
    // 
    let [currentIndex, setCurrentIndex] = useState( parseInt(window.sessionStorage.getItem('idx')) || 0)
    // 
    let [playlist] = useState( JSON.parse(window.sessionStorage.getItem('musiclist')) || [])
    // 
    let [statics, setstatic] = useState(JSON.parse(window.sessionStorage.getItem('musicstatic')) || {})
    // 计算属性,监听音乐播放停止操作
    let playorpause = useMemo(() => {
        setTimeout(() => {
            let img = document.querySelector('.changpian')
            if (play) {
                audioRef.current.play()
                img.style.animationPlayState = 'running'
            } else {
                audioRef.current.pause()
                img.style.animationPlayState = 'paused'
            }
        })
        return play
    }, [play])


    // 返回获取播放地址以及处理后的歌词
    const getmusicdetail = async () => {
        let { data: { data: [data] } } = await axios.get('http://localhost:3000/song/url?id=' + playlist[currentIndex])
        let { data: data2 } = await axios.get('http://localhost:3000/lyric?id=' + playlist[currentIndex])
        let {data:{songs:[songdet]}} = await axios('http://localhost:3000/song/detail?ids='+playlist[currentIndex])
        let word = data2.lrc.lyric.split('\n')
        let newWord = []
        word.slice(0, word.length - 1).forEach((item) => {
            let time = item.split(']')[0].slice(1,)
            let lyc = item.split(']')[1]
            if (lyc !== '') newWord.push({ time, lyc })
        })
        setstatic(songdet)
        setmusicurl(data)
        setword(newWord)
        window.sessionStorage.setItem('musicstatic', JSON.stringify(songdet))
        // if(musicurl.url === null){
        //     message.info('此歌曲没有版权');
        //     setCurrentIndex(++currentIndex)
        //     getmusicdetail()
        // }
    }


    // 进度条改变事件
    const timeUpdate = (e) => {
        let currentTime = format(document.querySelector('audio')['currentTime'])
        for (let i = 0; i < word.length; i++) {
            if (word[i + 1] && currentTime <= word[i + 1].time && currentTime >= word[i].time) {
                setcurrentlyc(i)
            }
        }
    }
    // 将时间处理成时分秒的格式
    const format = (value) => {
        if (!value) return ''
        let xiaoshu = (value % 1).toFixed(3)
        let interval = Math.floor(value)
        let minute = (Math.floor(interval / 60)).toString().padStart(2, '0')
        let second = (interval % 60).toString().padStart(2, '0')
        return `${minute}:${second}.${xiaoshu.split('.')[1]}`
    }


    const getTitle = (data) => {
        if (data.length > 15){
            return data.slice(0, 15)+'...'
        }else{
            return data
        }
    }


    return (
        <div className='musicdetail' style={{ height:"100%", width:"3.500rem", background: `url(${statics.al.picUrl}) top center no-repeat`, backgroundSize: '280% auto' }}>

            {/* 内包裹 */}
            <div className='bgdetail'>

                {/* 返回首页/上一级按钮 */}
                <div className='locationBtn'>
                    <div><LeftOutlined style={{ color: "#fff", fontSize: "0.2rem" }} onClick={() => { props.history.goBack()}} /></div>
                    <div className='fenge'></div>
                    <div><HomeFilled style={{ color: "#fff", fontSize: "0.2rem" }} onClick={() => { props.history.push('/') }} /></div>
                </div>

                {/* 歌曲名称 */}
                <div className='detailtitle' style={{ backgroundImage: statics.headColor }}>{getTitle(statics.name)}</div>

                {/* 歌曲内容，滚动条部分 */}
                <div className='detailcontent'>

                    {/* 滚动条部份 */}
                    <div className='gecizhuanpan'>

                        {/* 网易云logo， 下方style控制元素显示隐藏，隐藏显示歌词的第二种样式 */}
                        {
                            !getword && (
                                <div className='logo' style={getword ? { display: "none" } : {}}>
                                    <img src="http://p1.music.126.net/fL9ORyu0e777lppGU3D89A==/109951167206009876.jpg" alt="" />
                                    <span>网易云音乐</span>
                                </div>
                            )
                        }

                        {/* 中间转盘部分 下方style控制元素显示隐藏，隐藏显示歌词的第二种样式*/}
                        {
                            !getword && (
                                <div className='zhuanpan'>
                                    {
                                        !playorpause && (<PlayCircleTwoTone className='centericon' onClick={() => setplay(true)} />)
                                    }
                                    {
                                        playorpause && (<PauseCircleTwoTone className='centericon' onClick={() => setplay(false)} />)
                                    }
                                    <div className='changpian'>
                                        <img className='zhuanpanimg' src={statics.al.picUrl} alt="" />
                                    </div>
                                </div>
                            )
                        }
                        
                        {/* 歌词部分 */}
                        <div className='musicword' onClick={() => { setgetword(getword => !getword) }} style={getword ? { height: "85%", overflow: "none" } : { overflow: "hidden" }}>{/* style控制歌词部分高度，更改歌词样式 */}
                            <div style={getword ? { height: "85%", transform: `translateY(${2.1 + -(0.35 * (currentlyc - 1))}rem)` } : { transform: `translateY(${-(0.35 * (currentlyc - 1))}rem)`, overflow: "hidden" }}>{/* style控制歌词部分高度，更改歌词样式 */}
                                {
                                    word.map((item, index) => {
                                        return (
                                            <p key={index} className="words" style={currentlyc === index ? { color: '#fff', fontSize: "0.18rem", fontWeight: "550" } : {}}>
                                                {item.lyc}
                                            </p>
                                        )
                                    })
                                }
                            </div>
                        </div>


                        {/* 音频标签 */}
                        <audio
                            src={musicurl.url}
                            ref={audioRef}
                            onTimeUpdate={(e) => timeUpdate(e)}
                            onEnded={() => {
                                setplay(false)
                                currentIndex += 1
                                if (currentIndex >= playlist.length) currentIndex = 0
                                setTimeout(() => {
                                    window.sessionStorage.setItem('idx', currentIndex)
                                    setCurrentIndex(currentIndex)
                                    getmusicdetail()
                                    // getmusicdetail()
                                    audioRef.current.play()
                                },1000)
                            }}
                            controls
                            autoPlay
                            className='audios'
                            onPause={() => { setplay(false) }}
                            onPlay={() => setplay(true)}
                        >
                        </audio>
                    </div>
                </div>
            </div>
        </div>
    )
}
